package com.mrlv.common.http;


import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class HttpUtils {

	/**
	 * get请求
	 * @return
	 */
	public static String doGet(String url) {
		try {
			// 定义HttpClient
			CloseableHttpClient httpClient = HttpClientBuilder.create().build();
			// 发送get请求
			HttpGet request = new HttpGet(url);
			HttpResponse response = httpClient.execute(request);

			/** 请求发送成功，并得到响应 **/
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				/** 读取服务器返回过来的json字符串数据 **/
				String strResult = EntityUtils.toString(response.getEntity());
				return strResult;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * post请求(用于key-value格式的参数)
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doPost(String url, Map params, Map<String, String> header) {

		BufferedReader in = null;
		try {
			// 定义HttpClient
			CloseableHttpClient httpClient = HttpClientBuilder.create().build();
			// 实例化HTTP方法
			HttpPost request = new HttpPost();
			request.setURI(new URI(url));

			if (header != null)

			// 传入请求头
			if (header != null) {
				// request.setHeader("Content-Type", "application/x-www-form-urlencoded");
				header.keySet().stream().forEach(e -> request.setHeader(e, header.get(e)));
			}

			// 设置参数
			if (params != null) {
				List<NameValuePair> nvps = header.keySet().stream()
						.map(e -> new BasicNameValuePair(e, String.valueOf(params.get(e))))
						.collect(Collectors.toList());
				request.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
			}

			HttpResponse response = httpClient.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			if (HttpStatus.SC_OK == statusCode) { // 请求成功
				in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
				StringBuffer sb = new StringBuffer();

				String NL = System.getProperty("line.separator");

				String line;
				while ((line = in.readLine()) != null) {
					sb.append(line + NL);
				}
				in.close();
				return sb.toString();
			} else {
				log.error("请求失败");
				//TODO
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("请求异常");
			//TODO
			return null;
		} finally {
			if (in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * post请求（用于请求json格式的参数）
	 * @param url
	 * @param paramsJSON
	 * @return
	 */
	public static String doPost(String url, String paramsJSON) throws Exception {

		CloseableHttpClient httpClient = HttpClientBuilder.create().build();

		HttpPost httpPost = new HttpPost(url);// 创建httpPost
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Content-Type", "application/json");
		//将Json数据的参数添加在请求体中
		StringEntity entity = new StringEntity(paramsJSON, StandardCharsets.UTF_8);
		httpPost.setEntity(entity);
		CloseableHttpResponse response = null;

		response = httpClient.execute(httpPost);
		int stateCode = response.getStatusLine().getStatusCode();
		if (HttpStatus.SC_OK == stateCode) {
			HttpEntity responseEntity = response.getEntity();
			String jsonString = EntityUtils.toString(responseEntity);
			return jsonString;
		} else {
			log.error("请求返回:" + stateCode + "(" + url + ")");
			return null;
		}
	}

}
